// pages/yoshop/user/mycourse.js
let _this;
let common = require('../../utils/common.js');
let Bmob = require('../../utils/bmob.js');
let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    'joinedTotal': 0,
    'completedTotal': 0,
    'durationOfStudy': 0,
    'courses': []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    _this = this
    Bmob.initialize("8bbd2fa87eece23337234b59c300fb2e", "0422786c4a1502011b37da0d9f437770")
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.setNavigationBarTitle({
      title: '我的课程',
    })

    _this.getMyCourse()
    _this.getProfile()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 获取我的课程
   */
  getMyCourse: function() {

    wx.showLoading({
      title: '获取数据中...',
    })

    let _urlMyCourse = 'classes/JoinCourse?include=article[Title|ResourceTotal|ImageUrl]&where={"user":"' + wx.getStorageSync('bmobObjectId') + '"}'

    App._get(_urlMyCourse, {}, function(res) {

      let _completedTotal = 0
      res.results.forEach(function(item, index, arr) {
        if (item.completedResTotal === item.article.ResourceTotal) {
          _completedTotal++
        }
      })

      _this.setData({
        'joinedTotal': res.results.length,
        'completedTotal': _completedTotal,
        'courses': res.results
      })

      wx.hideLoading()
    })
  },

  /**
   * 获取学习时长
   */
  getProfile: function() {
    let _url = 'classes/Profile/' + wx.getStorageSync('profileId')

    App._get(_url, {}, function(res) {
      console.log(res)
      _this.setData({
        'durationOfStudy': res.durationOfStudy
      })
    })
  }
})